package com.lib.framework.manager

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Bundle
import com.lib.framework.ext.Weak

/**
 * context 管理
 */
class ContextManager {

    companion object {

        // 弱上下文引用
        private var weakContext: Context? by Weak()

        var context: Context
            get() = this.weakContext ?: applicationContext  //  降级成返回应用上下文
            set(value) {
                this.weakContext = value  // 转换成Weak链接，防止内存泄漏 - 后面一般是动态注入Activity作为上下文
            }

        lateinit var applicationContext: Application

        /**
         * 注册 页面 的生命周期，保存当前页面的 Context
         */
        @JvmStatic
        fun registerActivityLifecycleCallbacks(application: Application) {
            applicationContext = application

            application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
                override fun onActivityPaused(activity: Activity?) {

                }

                override fun onActivityResumed(activity: Activity?) {
                    activity?.let {
                        context = it
                    }
                }

                override fun onActivityStarted(activity: Activity?) {

                }

                override fun onActivityDestroyed(activity: Activity?) {
                    activity?.let {
                        if (context == it) {
                            context = applicationContext
                        }
                    }
                }

                override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {

                }

                override fun onActivityStopped(activity: Activity?) {

                }

                override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
                    activity?.let {
                        context = it
                    }
                }
            })
        }
    }

}